//
//  MainWindow.cpp
//  Editor
//
//  Created by Jeppe Nielsen on 10/19/14.
//  Copyright (c) 2014 Jeppe Nielsen. All rights reserved.
//

#include "MainWindow.hpp"
#include <QtWidgets/QtWidgets>
#include "ProjectWindow.hpp"
#include "Project.hpp"
#include <iostream>

void MainWindow::AddToolWindow(ToolWindow *toolWindow) {
    toolWindows.push_back(toolWindow);
}

void MainWindow::Initialize() {
    setWindowTitle(tr("Nano Editor"));
    //setUnifiedTitleAndToolBarOnMac(true);
    
    timer.setSingleShot(false);
    connect(&timer, SIGNAL(timeout()), this, SLOT(Update()));
    timer.start(16);

    CreateMenus();
    
    this->setDockNestingEnabled(true);
    this->setTabPosition(Qt::AllDockWidgetAreas, QTabWidget::North);
    
    for (int i=0; i<toolWindows.size(); i++) {
        toolWindows[i]->Create(this, toolWindowsMenu, &context);
    }
    
    projectWindow.ProjectCreated += event_handler(this, &MainWindow::ProjectCreated);
    ProjectCreated("/Projects/Nano/trunk/Editor/TestProjects");
}

void MainWindow::NewProject() {
   projectWindow.show();
}

void MainWindow::CreateMenus() {
    
    fileMenu = menuBar()->addMenu(QString("File"));
    
    {
        fileProjectNew = new QAction(QString("New Project"), this);
        fileProjectNew->setShortcuts(QKeySequence::New);
        fileMenu->addAction(fileProjectNew);
    
        connect(fileProjectNew, SIGNAL(triggered()), this, SLOT(NewProject()));
    }
    {
        fileSave = new QAction(QString("Save"), this);
        fileSave->setShortcut(QKeySequence::Save);
        fileMenu->addAction(fileSave);
    
        connect(fileSave, SIGNAL(triggered()), this, SLOT(Save()));
    }
    
    gameMenu = menuBar()->addMenu("Game");
    {
        gameCompile = new QAction(QString("Build"), this);
        gameCompile->setShortcut(QKeySequence("Ctrl+B"));
        gameMenu->addAction(gameCompile);
        
        connect(gameCompile, SIGNAL(triggered()), this, SLOT(Compile()));
    }
    {
        gameStep = new QAction(QString("Step"), this);
        gameStep->setShortcut(QKeySequence("Ctrl+P"));
        gameMenu->addAction(gameStep);
        
        connect(gameStep, SIGNAL(triggered()), this, SLOT(ProjectStep()));
    }
    
    {
        toolWindowsMenu = menuBar()->addMenu(QString("&Windows"));
    }
}


void MainWindow::ProjectCreated(QString projectPath) {
    context.CreateNewProject(projectPath);
}

void MainWindow::Save() {
    for (int i=0; i<toolWindows.size(); i++) {
        toolWindows[i]->Save();
    }
}

void MainWindow::Compile() {
    if (!(context.CurrentProject)) return;
    context.CurrentProject()->Build();
}

void MainWindow::ProjectStep() {
    if (!(context.CurrentProject)) return;
     context.CurrentProject()->Step();
}

void MainWindow::Update() {
    if (context.CurrentProject()) {
        context.CurrentProject()->Update(1.0f / 60.0f);
    }
}


